package com.haimi.shiguang.net;

import android.text.TextUtils;
import android.util.Log;

import com.haimi.shiguang.framework.HeaderCache;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 统一追加Header
 *
 * @author changsunhaipeng
 */

public class AppendHeaderParamIntercepter implements Interceptor {
    public String requestId;

    public AppendHeaderParamIntercepter() {
    }

    public AppendHeaderParamIntercepter(String requestId) {
        this.requestId = requestId;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Headers.Builder builder = request
                .headers()
                .newBuilder();
        if (TextUtils.isEmpty(requestId)) {
            requestId = HeaderCache.requestId;
        }
        //统一追加Header参数
        Headers newBuilder = builder
                .add("p_u", HeaderCache.uid)
                .add("p_s", HeaderCache.sessionId)
                .add("p_t", HeaderCache.token)
                .add("r_i", requestId)
                .add("a_n", HeaderCache.appName)
                .add("os", HeaderCache.os)
                .add("os_iv", HeaderCache.osInnerVersion)
                .add("os_ov", HeaderCache.osOutVersion)
                .add("c_n", HeaderCache.mobileName)
                .build();

        Request newRequest = request.newBuilder()
                .headers(newBuilder)
                .build();
        Log.d("retrofit-header", newRequest.headers().toString());

        return chain.proceed(newRequest);
    }
}